const hre = require("hardhat");

async function main() {
  console.log("开始部署 DigitalCollectionNFT 合约...");

  // 获取部署账户
  const [deployer] = await hre.ethers.getSigners();
  console.log("部署账户:", deployer.address);

  // 获取账户余额
  const balance = await hre.ethers.provider.getBalance(deployer.address);
  console.log("账户余额:", hre.ethers.formatEther(balance), "ETH");

  // 部署合约
  const DigitalCollectionNFT = await hre.ethers.getContractFactory("DigitalCollectionNFT");
  console.log("\n正在部署合约...");
  
  const nft = await DigitalCollectionNFT.deploy();
  await nft.waitForDeployment();

  const contractAddress = await nft.getAddress();
  console.log("✅ DigitalCollectionNFT 合约已部署到:", contractAddress);

  // 显示合约信息
  console.log("\n合约信息:");
  console.log("- 名称:", await nft.name());
  console.log("- 符号:", await nft.symbol());
  console.log("- Owner:", await nft.owner());
  console.log("- 手续费接收地址:", await nft.feeRecipient());
  console.log("- 平台手续费:", Number(await nft.platformFeePercent()) / 100, "%");

  // 等待几个区块确认（仅在测试网/主网）
  if (hre.network.name !== "hardhat" && hre.network.name !== "localhost") {
    console.log("\n等待区块确认...");
    await nft.deploymentTransaction().wait(5);
    console.log("✅ 已确认");

    // 验证合约（如果配置了 Etherscan API）
    if (process.env.ETHERSCAN_API_KEY) {
      console.log("\n开始验证合约...");
      try {
        await hre.run("verify:verify", {
          address: contractAddress,
          constructorArguments: [],
        });
        console.log("✅ 合约验证成功");
      } catch (error) {
        console.log("⚠️ 合约验证失败:", error.message);
      }
    }
  }

  console.log("\n部署完成! 🎉");
  console.log("\n请保存以下信息:");
  console.log("================================");
  console.log("合约地址:", contractAddress);
  console.log("网络:", hre.network.name);
  console.log("部署者:", deployer.address);
  console.log("================================");

  // 保存部署信息到文件
  const fs = require("fs");
  const deploymentInfo = {
    network: hre.network.name,
    contractAddress: contractAddress,
    deployer: deployer.address,
    timestamp: new Date().toISOString(),
    contractName: "DigitalCollectionNFT",
  };

  const deploymentsDir = "./deployments";
  if (!fs.existsSync(deploymentsDir)) {
    fs.mkdirSync(deploymentsDir);
  }

  fs.writeFileSync(
    `${deploymentsDir}/${hre.network.name}.json`,
    JSON.stringify(deploymentInfo, null, 2)
  );

  console.log(`\n部署信息已保存到: ${deploymentsDir}/${hre.network.name}.json`);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

